package com.loveprogrammer.base.websocket;

import com.alibaba.fastjson2.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive;

/**
 * @ClassName WebSocketTestHandler
 * @Description TODO
 * @Author admin
 * @Date 2024/3/4 11:34
 * @Version 1.0
 */
@Slf4j
public class WebSocketTestHandler extends SimpleChannelInboundHandler<Object> {

    private WebSocketServerHandshaker handshaker;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加连接
        log.debug("客户端加入连接："+ctx.channel());
        ChannelGroupExecutor.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连接
        log.debug("客户端断开连接："+ctx.channel());
        ChannelGroupExecutor.removeChannel(ctx.channel());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.debug("收到消息："+ msg);
        if (msg instanceof FullHttpRequest){
            //以http请求形式接入，但是走的是websocket
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        }else if (msg instanceof WebSocketFrame){
            //处理websocket客户端的消息
            handlerWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    /**
     * 唯一的一次http请求，用于创建websocket
     * */
    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest fhr) {
        //要求Upgrade为websocket，过滤掉get/Post
        if (!fhr.decoderResult().isSuccess()
                || (!"websocket".equals(fhr.headers().get("Upgrade")))) {
            //若不是websocket方式，则创建BAD_REQUEST的req，返回给客户端
            sendHttpResponse(ctx, fhr, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://localhost:9091/websocket", null, false);
        handshaker = wsFactory.newHandshaker(fhr);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory
                    .sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), fhr);
        }
    }

    /**
     * 拒绝不合法的请求，并返回错误信息
     * */
    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
        if (!isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    /***
     * 处理WebSocketFrame格式的请求数据，有IETF发布的WebSocket RFC，定义了6种帧，Netty为它们都提供了一个POJO实现。
     * BinaryWebSocketFrame——包含了二进制数
     * TextWebSocketFrame——包含了文本数据
     * ContinuationWebSocketFrame——包含属于上一个BinaryWebSocketFrame或TextWebSocketFrame的文本数据或者二进制数据
     * CloseWebSocketFrame——表示一个CLOSE请求，包含一个关闭的状态码和关闭的原因
     * PingWebSocketFrame——请求传输一个PongWebSocketFrame
     * PongWebSocketFrame——作为一个对于PingWebSocketFrame的响应被发送
     * @param ctx
     * @param msg
     */
    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame msg) {
        // 关闭链路的指令
        if(msg instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(),((CloseWebSocketFrame) msg).retain());
        }
        // 如果是ping指令 返回pong
        if(msg instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(msg.content().retain()));
            return;
        }
        // 如果是文本消息
        if(msg instanceof TextWebSocketFrame) {
            // 返回应答消息
            String request = ((TextWebSocketFrame) msg).text();
            log.info("收到消息" + request);
            TextWebSocketFrame tws = new TextWebSocketFrame(request);
            ctx.channel().writeAndFlush(tws);
            // 群发
            // ChannelGroupExecutor.send2All(tws);
        }
        // 如果是二进制
        if(msg instanceof BinaryWebSocketFrame) {

        }
    }

}
